package com.ujcms.cms.core;

import org.owasp.html.HtmlPolicyBuilder;
import org.owasp.html.PolicyFactory;
import org.owasp.html.examples.EbayPolicyExample;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author 10100
 * @license (C) Copyright 2020-2050,  Corporation Limited.
 * @contact wang.he@cpe-smartcity.com
 * @date 2025-03-06 13:01
 * @description html prase config
 */
@Configuration
public class HtmlPolicyConfig {


    /**
     * HTML过滤器。防止跨站攻击。
     */
    @Bean
    public PolicyFactory policyFactory() {
        return EbayPolicyExample.POLICY_DEFINITION.and(new HtmlPolicyBuilder()
                // 允许视频元素
                .allowElements("video").allowAttributes("controls", "preload", "width", "height", "src").onElements("video")
                .allowElements("audio").allowAttributes("controls", "preload", "width", "height", "src").onElements("audio")
                .allowElements("source").allowAttributes("src", "type").onElements("source")
                .allowElements("a").allowAttributes("target").matching(true, "_blank").onElements("a")
                // 允许 figcaption 标签，通常与 figure 搭配使用
                .allowElements("figure")
                // 允许 img 标签，因为 figure 中可能包含图片, 允许 img 标签的 src 和 alt 属性
                .allowElements("img").allowAttributes("src", "alt").onElements("img").allowUrlProtocols("http", "https")
                .toFactory());
    }
}